package facilius.controller.action.espaco;

import facilius.model.ServiceLocator;
import facilius.model.pojo.Frequencia;
import facilius.model.pojo.UsuarioCurso;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.mentawai.core.BaseAction;

/**
 *
 * @author Graciano
 */
public class EspacoFrequenciaReadAction extends BaseAction {

    @Override
    public String execute() throws Exception {
        String consequence = ERROR;
        try {
            Map<String, Object> criteria = new HashMap<String, Object>();
            criteria.put("usuarioId", session.getAttribute("userId").toString());
            List<UsuarioCurso> users = ServiceLocator.getUsuarioCursoService().readByCriteria(criteria);

            criteria = new HashMap<String, Object>();
            criteria.put("matricula", users.get(0).getMatricula());
            List<Frequencia> listFrequencia = ServiceLocator.getFrequenciaService().readByCriteria(criteria);



            boolean possui = false;
            List<Map<String, Object>> pojos = new ArrayList<Map<String, Object>>();
            for (Frequencia frequencia : listFrequencia) {
                
                possui = false;
                
                Map<String, Object> mapFreq = new HashMap<String, Object>();
                for (int i = 0; i < pojos.size(); i++) {
                    if (pojos.get(i).get("turma") != null && pojos.get(i).get("turma").toString().equalsIgnoreCase(frequencia.getAula().getTurma().toString())){
                        mapFreq = pojos.get(i);
                        possui = true;
                        break;
                    }
                }
                criteria = new HashMap<String, Object>();
                criteria.put("matricula", users.get(0).getMatricula());
                criteria.put("aulaId", frequencia.getAula().getId());
                List<Frequencia> list = ServiceLocator.getFrequenciaService().readByCriteria(criteria);

                mapFreq.put("turma", frequencia.getAula().getTurma().toString());

                for (Frequencia frequencia1 : list) {
                    if (!frequencia1.isStatus()){
                        if (mapFreq.get("faltas") != null){
                            mapFreq.put("faltas",(Integer.parseInt(mapFreq.get("faltas").toString()) + 1));
                        }else{
                            mapFreq.put("faltas",1);
                        }
                    }else
                        if (mapFreq.get("faltas") == null)
                            mapFreq.put("faltas",0);

                }

                if (!possui)
                    pojos.add(mapFreq);
            }

            output.setValue("pojos", pojos);

            consequence = SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return consequence;
    }
}
